package net.csdn.business.common.config.ocr;

import cn.authing.core.types.S;
import com.alibaba.fastjson2.JSON;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.*;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.domain.vo.enterprise.BusinessLicenseVo;
import net.csdn.business.common.domain.vo.enterprise.IdcardVo;
import net.csdn.business.common.enums.ResultCodeEnum;
import net.csdn.business.common.utils.ExceptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * @ClassName AliyunOcrWrapperFacade
 * @Description TODO
 * @Author lzs
 * @Date 2024/4/18
 **/
@Component
@Slf4j
public class AliyunOcrWrapperFacade {
    @Autowired
    private AliYunOcrConfig aliYunOcrConfig;

    public IdcardVo idcardRecognition(InputStream body){
        RecognizeIdcardRequest request = new RecognizeIdcardRequest();
        RuntimeOptions runtime = new RuntimeOptions();
        request.setBody(body);
        return this.getIdcardInfo(request,runtime);
    }
    public IdcardVo idcardRecognitionByUrl(String url){
        RecognizeIdcardRequest request = new RecognizeIdcardRequest();
        RuntimeOptions runtime = new RuntimeOptions();
        request.setUrl(url);
        return this.getIdcardInfo(request,runtime);
    }

    public IdcardVo getIdcardInfo(RecognizeIdcardRequest request,RuntimeOptions runtime) {
        IdcardVo idcardInfo = null;
        try {
            Client client = aliYunOcrConfig.createClient();
            RecognizeIdcardResponse resp = client.recognizeIdcardWithOptions(request, runtime);
            log.info("身份证识别结果:{}", JSON.toJSONString(resp));
            RecognizeIdcardResponseBody responseBody = resp.getBody();
            if(responseBody.getCode() != null){
                log.error("身份证识别失败:{}",responseBody.getMessage());
                ExceptionUtil.throwBizException(ResultCodeEnum.IDCARD_RECOGNITION_ERROR,responseBody.getMessage());
            }
            String data =  responseBody.getData();
            idcardInfo = JSON.parseObject(data).getJSONObject("data").getJSONObject("face").getObject("data", IdcardVo.class);
            return idcardInfo;

        } catch (TeaException error) {
            log.error("身份证识别异常:{},诊断地址:{}",error.getMessage(),error.getData().get("Recommend"));
            ExceptionUtil.throwBizException(ResultCodeEnum.IDCARD_RECOGNITION_ERROR);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            log.error("身份证识别异常:{},诊断地址:{}",error.getMessage(),error.getData().get("Recommend"));
            ExceptionUtil.throwBizException(ResultCodeEnum.IDCARD_RECOGNITION_ERROR);
        }
        return idcardInfo;
    }


    /**
     * @Desc: 营业执照识别
     * @author: lzs
     * @date: 2024/4/18
     */
    public BusinessLicenseVo businessLicenseRecognition(InputStream body){
        RecognizeBusinessLicenseRequest request = new RecognizeBusinessLicenseRequest();
        request.setBody(body);
        RuntimeOptions runtime = new RuntimeOptions();
        return this.getBusinessLicenseInfo(request, runtime);
    }

    public BusinessLicenseVo businessLicenseRecognitionByUrl(String url){
        RecognizeBusinessLicenseRequest request = new RecognizeBusinessLicenseRequest();
        request.setUrl(url);
        RuntimeOptions runtime = new RuntimeOptions();
        return this.getBusinessLicenseInfo(request, runtime);
    }

    public BusinessLicenseVo getBusinessLicenseInfo(RecognizeBusinessLicenseRequest request,RuntimeOptions runtime){
        BusinessLicenseVo businessLicenseVo = null;
        try {
            Client client = aliYunOcrConfig.createClient();
            RecognizeBusinessLicenseResponse resp = client.recognizeBusinessLicenseWithOptions(request, runtime);
            log.info("营业执照识别结果:{}", JSON.toJSONString(resp));
            RecognizeBusinessLicenseResponseBody responseBody = resp.getBody();
            if(responseBody.getCode() != null){
                log.error("营业执照失败:{}",responseBody.getMessage());
                ExceptionUtil.throwBizException(ResultCodeEnum.BUSINESS_LICENSE_RECOGNITION_ERROR,responseBody.getMessage());
            }
            String data =  responseBody.getData();
            businessLicenseVo = JSON.parseObject(data).getObject("data",BusinessLicenseVo.class);
            return businessLicenseVo;
        } catch (TeaException error) {
            log.error("营业执照识别失败:{},诊断地址:{}",error.getMessage(),error.getData().get("Recommend"));
            ExceptionUtil.throwBizException(ResultCodeEnum.BUSINESS_LICENSE_RECOGNITION_ERROR);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            log.error("营业执照识别异常:{},诊断地址:{}",error.getMessage(),error.getData().get("Recommend"));
            ExceptionUtil.throwBizException(ResultCodeEnum.BUSINESS_LICENSE_RECOGNITION_ERROR);
        }
        return businessLicenseVo;
    }
    /**
     * @Desc: 上传文件
     * @author: lzs
     * @date: 2024/4/22
     */
    public String uploadOssFile(String filePath,byte[] fileByte){
        InputStream inputStream = new ByteArrayInputStream(fileByte);
        OSS ossClient = aliYunOcrConfig.createOSSClient();
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliYunOcrConfig.getBucketName(), filePath, inputStream);
        // 上传文件。
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        log.info("上传oss文件结果：{}", JSON.toJSON(result));
        // 关闭OSSClient。
        ossClient.shutdown();
        return aliYunOcrConfig.getEndpointWithBucket()+filePath;
    }

    /**
     * @Desc: 获取文件路径
     * @author: lzs
     * @date: 2024/4/22
     */
    public byte[] getFileByte(String filePath) throws IOException{
        OSS ossClient = aliYunOcrConfig.createOSSClient();
        OSSObject ossObject = ossClient.getObject(aliYunOcrConfig.getBucketName(), filePath);
        InputStream inputStream  = ossObject.getObjectContent();
        byte[] fileBytes = readInputStreamToByteArray(inputStream);
        return fileBytes;
    }
    public byte[] readInputStreamToByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null){
                outputStream.close();
            }
        }
    }

    public String getCasualUrl(String filePath){
        OSS ossClient = aliYunOcrConfig.createOSSClient();
        URL signedUrl = null;
        try {
            // 指定生成的签名URL过期时间，单位为毫秒。本示例以设置过期时间为1小时为例。
            Date expiration = new Date(new Date().getTime() + 120 * 1000L);

            // 生成签名URL。
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(aliYunOcrConfig.getBucketName(), filePath, HttpMethod.GET);
            // 设置过期时间。
            request.setExpiration(expiration);
            // 通过HTTP GET请求生成签名URL。
            signedUrl = ossClient.generatePresignedUrl(request);
            return signedUrl.toString();

        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS,but was rejected with an error response for some reason. 获取文件失败:{},异常:{]",filePath,oe.getErrorMessage());

        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered \"\n" +
                    "                    + \"a serious internal problem while trying to communicate with OSS, \"\n" +
                    "                    + \"such as not being able to access the network. 获取文件失败:{},异常:{]",filePath,ce.getMessage());
        }
        return null;
    }
}
